package com.xiaohong.jwt.controller;

import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author : xiaohong
 * @date : 2021/4/30 11:37
 */
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * JWT令牌模式
     * 获取令牌
     * http://localhost:8001/oauth/token post模式 basic auth模式 输入授权客户端的用户名和密码
     * 加入请求体
     * grant_type:password username:xiaohong password:xiaohong scope:all
     * 得到令牌设置Authorization请求头后访问资源
     * http://localhost:8001/user/jwt/getCurrentUser Bearer Token令牌 Bearer大小写都可
     */

    /**
     * 获取当前用户
     * @param authentication
     * @return
     */
    @RequestMapping("/jwt/getCurrentUser")
    public Object getCurrentUser(Authentication authentication, HttpServletRequest httpServletRequest){
        String head = httpServletRequest.getHeader("Authorization");
        // 获取令牌 加空格7个
        String token = head.substring(head.indexOf("bearer") + 7);
        // 解析
        return Jwts.parser()
                .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }

}
